
import 'dart:convert';
import 'package:bot_toast/bot_toast.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:gun/http/api.dart';
import 'package:gun/main.dart';
import 'package:gun/page/index_page.dart';
import 'package:gun/util/toast_util.dart';
import 'setting_common_page.dart';

class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {

  String _username = '';
  String _psw = '';
  RxBool check = RxBool(false);

  @override
  initState() {
    super.initState();
    if(settingEntity.rememberPaw != null){
      check.value = settingEntity.rememberPaw!;
      if(check.value){
        if(settingEntity.username != null){
          _username = settingEntity.username!;
        }
        if(settingEntity.psw != null){
          _psw = settingEntity.psw!;
        }
      }
    }
  }

  _accountWidget(){
    return Container(
      width: 340.w,
      decoration:BoxDecoration(
        color: Colors.white54,
        borderRadius: BorderRadius.all(Radius.circular(6.r)),
      ),
      padding: EdgeInsets.only(left:10.r,right: 10.r),
      margin:  EdgeInsets.only(bottom: 10.r,top: 10.r),
      child: Row(
        children: [
          const Icon(Icons.person_outline_rounded,color: Colors.white,),
          SizedBox(width: 4.w,),
          SizedBox(
            width: 280.w,
            child: TextField(
                minLines: 1,
                textInputAction: TextInputAction.search,
                onChanged: (input){
                  _username = input;
                },
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.only(top: 16.r,bottom: 16.r),
                  isCollapsed: true,
                  hintText: "请输入管理员账号",
                  border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.white,fontSize: 20.sp)
                ),
                style: TextStyle(color: Colors.white,fontSize: 20.sp),
                controller: TextEditingController.fromValue(TextEditingValue(
                    text: _username,
                    selection: TextSelection.fromPosition(
                        TextPosition(
                            affinity: TextAffinity.downstream,
                            offset: _username.length))
                )),
            ),

          ),
        ],
      )
    );
  }

  RxBool passwordVisible = RxBool(false);

  _passwordWidget(){
    return Container(
        width: 340.w,
        decoration:BoxDecoration(
          color: Colors.white54,
          borderRadius: BorderRadius.all(Radius.circular(6.r)),
        ),
        padding: EdgeInsets.only(left:10.r,right: 10.r),
        margin:  EdgeInsets.only(bottom: 5.r,top: 10.r),
        child: Obx(() => Row(
          children: [
            const Icon(Icons.lock_outline,color: Colors.white,),
            SizedBox(width: 4.w,),
            SizedBox(
              width: 255.w,
              child: TextField(
                  obscureText: !passwordVisible.value,
                  minLines: 1,
                  textInputAction: TextInputAction.search,
                  onChanged: (input){
                    _psw = input;
                  },
                  decoration: InputDecoration(
                      contentPadding: EdgeInsets.only(top: 16.r,bottom: 16.r),
                      isCollapsed: true,
                      hintText: "请输入密码",
                      border: InputBorder.none,
                      hintStyle: TextStyle(color: Colors.white,fontSize: 20.sp)
                  ),
                  style: TextStyle(color: Colors.white,fontSize: 20.sp),
                  controller: TextEditingController.fromValue(TextEditingValue(
                      text: _psw,
                      selection: TextSelection.fromPosition(
                          TextPosition(
                              affinity: TextAffinity.downstream,
                              offset: _psw.length))
                  )),
              ),
            ),
            SizedBox(width: 4.w,),
            InkWell(
              onTap: (){
                passwordVisible.value = !passwordVisible.value;
              },
              child: Icon(passwordVisible.value?Icons.remove_red_eye:Icons.remove_red_eye_outlined,color: Colors.white,),
            )
          ],
        ))
    );
  }


  _rememberPasswordWidget(){
    return Obx(() => Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        Checkbox(
           checkColor: Colors.white,
           side: MaterialStateBorderSide.resolveWith((Set<MaterialState> states) {
                return const BorderSide(width: 2, color: Colors.white);
            }),
           value: check.value,
           onChanged: (value){
             check.value = !check.value;
             settingEntity.rememberPaw = check.value;
           }
        ),
        Text("记住密码",style: TextStyle(fontSize: 14.sp,color: Colors.white),)
      ],
    ));
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        body: Container(
            width: double.infinity,
            height: double.infinity,
            padding: EdgeInsets.only(left: 30.r,right: 30.r),
            decoration: const BoxDecoration(
              image: DecorationImage(
                fit: BoxFit.fill,
                image: AssetImage(
                  "assets/images/bg.png",
                ),
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 20.h,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      InkWell(
                        onTap: (){
                          Get.to(()=>const SettingCommon());
                        },
                        child:Image.asset("assets/images/setting.png",width: 60.w,fit: BoxFit.fitWidth,),
                      ),
                  ],
                ),
                SizedBox(height: 60.h,),
                Image.asset("assets/images/login_title.png",width: 300.w,fit: BoxFit.fitWidth,),
                SizedBox(height: 80.h,),
                Text('欢迎登录！',style: TextStyle(fontSize: 26.sp,color: Colors.white,fontWeight: FontWeight.bold),),
                _accountWidget(),
                _passwordWidget(),
                _rememberPasswordWidget(),
                SizedBox(height: 70.h,),
                InkWell(
                  onTap: () async {
                    if(_username.isEmpty){
                      toastWarn('管理员账号不能为空');
                      return;
                    }
                    if(_psw.isEmpty){
                      toastWarn('密码不能为空');
                      return;
                    }
                    BotToast.showLoading();
                    var result = await login( _username, _toMd5(_psw));
                    BotToast.closeAllLoading();
                    if(result != null){
                      if(check.value){
                        settingEntity.username = _username;
                        settingEntity.psw = _psw;
                      }else{
                        settingEntity.username = null;
                        settingEntity.psw = null;
                      }
                      final box = GetStorage();
                      box.write('setting_entity', settingEntity.toJson());
                      currentTask.uid = result;
                      Get.off(()=> const Index());
                    }
                  },
                  child: Align(child: Image.asset("assets/images/icon_log_on.png",width: 300.w,fit: BoxFit.fitWidth,),),
                ),
                SizedBox(height: 60.h,),
                Align(child: Text('浙江轩毅信息技术有限公司',style: TextStyle(fontSize: 14.sp,color: Colors.white),),)
              ],
            )
        ),
      ),
    );
  }

  String _toMd5(String data) {
    var content = const Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    return digest.toString().toUpperCase();
  }
}